package gui

import (
	"fmt"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"

	"pass-tree/internal/gui/welcome"
	"pass-tree/internal/gui/windows"
	"pass-tree/internal/logic/models"
	"pass-tree/internal/logic/services"
)

type MainWindow struct {
	Apps            fyne.App
	Window          fyne.Window
	Services        *services.Application
	Version         string
	CurrentSelectID *string //当前选中的ID
}

// 在 gui 包中
func NewMainWindow(apps fyne.App, win fyne.Window) *MainWindow {
	return &MainWindow{
		Apps:     apps,
		Window:   win,
		Services: &services.Application{Win: win},
		// 其他初始化
	}
}

var topWindow fyne.Window

var tree *widget.Tree

// 列表索引(用于显示左侧列表)
var dataIndex map[string][]string

// 列表数据
var TreeTabData = make(map[string]services.TreeTabInfo)

var setTreeTab func(t services.TreeTabInfo)

func (ui *MainWindow) MakeUI() fyne.CanvasObject {

	content := container.NewStack()
	// content.Hide()
	title := widget.NewLabel("Component name")
	intro := widget.NewLabel("An introduction would probably go\nhere, as well as a")
	//刷新
	refreshBtn := widget.NewButton("", func() {})
	refreshBtn.Icon = theme.ViewRefreshIcon()
	addBtn := widget.NewButton("添加", func() {})
	/* douFuJingLingBtn := widget.NewButton("导入抖服", func() {

	}) */
	editCategoryBtn := widget.NewButton("编辑分类", func() {})
	deleteCategoryBtn := widget.NewButton("删除分类", func() {})
	// testBtn := components.NewButton("测试", func() {})
	intro.Wrapping = fyne.TextWrapWord
	setTreeTab = func(t services.TreeTabInfo) {
		if fyne.CurrentDevice().IsMobile() {
			child := ui.Apps.NewWindow(t.Info.Name)
			topWindow = child
			child.SetContent(t.View(topWindow))
			child.Show()
			child.SetOnClosed(func() {
				topWindow = ui.Window
			})
			return
		}
		if t.Info.Name == "首页" {
			title.Hide()
			intro.Hide()
			refreshBtn.Hide()
			addBtn.Hide()
			// douFuJingLingBtn.Hide()
			editCategoryBtn.Hide()
			deleteCategoryBtn.Hide()
		} else {
			title.Show()
			intro.Show()
			refreshBtn.Show()
			addBtn.Show()
			// douFuJingLingBtn.Show()
			editCategoryBtn.Show()
			deleteCategoryBtn.Show()
			title.SetText(t.Info.Name)
			intro.SetText(t.Info.Desc)
		}
		refreshBtn.OnTapped = func() {
			ui.RefreshTree()

			if t, ok := TreeTabData[*ui.CurrentSelectID]; ok {
				setTreeTab(t)
			}
		}
		addBtn.OnTapped = windows.ShowAddWindow(ui.Apps, t, func() {
			ui.RefreshTree()
			if t, ok := TreeTabData[t.Info.Name]; ok {
				setTreeTab(t)
			}
		})
		editCategoryBtn.OnTapped = func() {
			nameInput := widget.NewEntry()
			nameInput.SetPlaceHolder("请输入分类名称")
			nameInput.SetText(t.Info.Name)
			descInput := widget.NewEntry()
			descInput.SetPlaceHolder("请输入分类描述")
			descInput.SetText(t.Info.Desc)

			items := []*widget.FormItem{
				widget.NewFormItem("名称", nameInput),
				widget.NewFormItem("描述", descInput),
			}

			form := dialog.NewForm("编辑分类", "保存", "取消", items, func(b bool) {
				if !b {
					return
				}
				category := new(models.Category)
				category.Id = t.Info.Id
				category.Name = nameInput.Text
				category.Desc = descInput.Text
				if err := ui.Services.UpdateCategory(category); err != nil {
					fmt.Println("修改分类失败", err)
				}
				ui.RefreshTree()
				//修改完分类后重新显示
				if t, ok := TreeTabData[nameInput.Text]; ok {
					setTreeTab(t)
				}
			}, ui.Window)
			// 设置对话框大小
			form.Resize(fyne.NewSize(400, 200))
			form.Show()
		}

		deleteCategoryBtn.OnTapped = func() {

			cnf := dialog.NewConfirm("提示", "您是否要删除当前分类吗?", func(response bool) {
				if response {
					if err := ui.Services.DeleteCategory(t.Info.Id); err != nil {
						fmt.Println("修改分类失败", err)
					}
					//默认显示首页
					if t, ok := TreeTabData["首页"]; ok {
						setTreeTab(t)
					}
					ui.RefreshTree()
				}
			}, ui.Window)
			cnf.SetDismissText("取消")
			cnf.SetConfirmText("确认")
			cnf.Show()
		}
		content.Objects = []fyne.CanvasObject{t.View(ui.Window)}
		content.Refresh()
	}
	funcUiLayout := container.NewHBox(refreshBtn, addBtn, editCategoryBtn, deleteCategoryBtn, widget.NewLabel(""))
	// container.NewVBox(title, widget.NewSeparator(), intro, funcUiLayout)
	rightUiLayout := container.NewBorder(container.NewVBox(title, widget.NewSeparator(), intro, funcUiLayout), nil, nil, nil, content)

	// 调用 makeTreeTab 函数获取 fyne.CanvasObject 实例
	treeTab := ui.makeTreeTab(setTreeTab)
	// allLayout := container.NewHSplit(treeTab, rightUiLayout)
	// 创建水平分割容器
	allLayout := container.NewHSplit(treeTab, rightUiLayout)
	allLayout.Offset = 0.23 // 设置分割线位置
	return allLayout
}

// 创建主菜单
func (ui *MainWindow) CreateMenuItems() {

	addCategoryMenuItem := fyne.NewMenuItem("新建分类", ui.ShowCategoryWindow())
	exportMenuItem := fyne.NewMenuItem("导出", ui.exportFile())
	exportBackupsMenuItem := fyne.NewMenuItem("导出备份", ui.exportBackups())
	setMenuItem := fyne.NewMenuItem("设置", func() {})

	fileMenu := fyne.NewMenu("文件", addCategoryMenuItem, exportMenuItem, exportBackupsMenuItem, setMenuItem)

	/* addTplItem := fyne.NewMenuItem("添加模板", func() {})
	toolMenu := fyne.NewMenu("工具", addTplItem) */

	processDocMenuItem := fyne.NewMenuItem("文档", func() {

		/*
			// 读取 Markdown 文件
			content, err := ioutil.ReadFile("../README.md")
			if err != nil {
				log.Fatalf("无法读取文件: %v", err)
			}

			// 使用 blackfriday 解析 Markdown
			html := blackfriday.Run(content)

			// 创建临时 HTML 文件
			tmpFile, err := storage.Child(storage.NewFileURI("temp.html"))
			if err != nil {
				// dialog.ShowError(err, w)
				return
			}

			write, err := storage.Writer(tmpFile)
			if err != nil {
				// dialog.ShowError(err, w)
				return
			}
			write.Write([]byte(html))
			write.Close()

			uri := tmpFile.String()[7:] // 去除 "file://" 前缀
			utils.OpenBrowser(uri)
		*/

	})

	aboutMenuItem := fyne.NewMenuItem("关于", func() {
		window := fyne.CurrentApp().NewWindow("pass tree")
		content := "\n版本: " + ui.Version + "\n\n" + "作者: Raymond 工作室\n\n"
		window.SetContent(widget.NewLabel(content))
		window.Resize(fyne.NewSize(220, 100))
		window.Show()
	})
	helpMenu := fyne.NewMenu("帮助", processDocMenuItem, aboutMenuItem)

	menu := fyne.NewMainMenu(fileMenu, helpMenu)

	ui.Window.SetMainMenu(menu)
}

// 创建左侧树形菜单
func (ui *MainWindow) makeTreeTab(setTreeTab func(treeTab services.TreeTabInfo)) fyne.CanvasObject {
	/* data := map[string]services.List{
		"welcome": {"name"},
	} */
	dataIndex = ui.GetList()

	tree = widget.NewTree(
		func(id widget.TreeNodeID) []widget.TreeNodeID {
			return dataIndex[id]
		},
		func(id widget.TreeNodeID) bool {
			_, exists := dataIndex[id]
			return exists && len(dataIndex[id]) > 0
		},
		func(branch bool) fyne.CanvasObject {
			return widget.NewLabel("Template")
		},
		func(id widget.TreeNodeID, branch bool, node fyne.CanvasObject) {
			label := node.(*widget.Label)
			if branch {
				label.SetText("📁 " + id)
			} else {
				label.SetText("📄 " + id)
			}

		},
	)
	// 添加选择/点击事件监听
	tree.OnSelected = func(id widget.TreeNodeID) {
		// 这里可以添加你的点击处理逻辑
		ui.CurrentSelectID = &id
		if t, ok := TreeTabData[id]; ok {
			setTreeTab(t)
		}
	}

	// 添加取消选择事件监听
	tree.OnUnselected = func(id widget.TreeNodeID) {
		fmt.Printf("Unselected: %s\n", id)
	}
	// 监听数据变化
	go func() {
		tree.Refresh()
	}()

	//默认显示首页
	if t, ok := TreeTabData["首页"]; ok {
		setTreeTab(t)
	}

	addBtn := widget.NewButton("新建分类", func() {})
	addBtn.OnTapped = ui.ShowCategoryWindow()
	//搜索
	searchBtn := widget.NewButton("", func() {})
	searchBtn.Icon = theme.SearchIcon()
	searchBtn.OnTapped = func() {
		ui.SearchMakeTableUI()
	}
	//刷新
	refreshBtn := widget.NewButton("", func() {})
	refreshBtn.Icon = theme.ViewRefreshIcon()
	refreshBtn.OnTapped = func() {
		ui.RefreshTree()
	}

	funcUiLayout := container.NewHBox(addBtn, searchBtn, refreshBtn, widget.NewLabel(""))
	return container.NewBorder(funcUiLayout, nil, nil, nil, tree)
}

// 刷新左侧列表
func (ui *MainWindow) RefreshTree() {
	dataIndex = ui.GetList()
	tree.Refresh()
}

// 左侧列表
func (ui *MainWindow) GetList() map[string][]string {
	//列表索引(用于显示左侧列表)
	dataListIndex := make(map[string][]string)

	lists, _ := ui.Services.GetCategory()
	//一级列表
	var firstLevelList []string
	firstLevelList = append(firstLevelList, "首页")
	for _, v := range lists {
		// 一级列表
		if v.Pid == 0 {
			firstLevelList = append(firstLevelList, v.Name)
		}
	}
	dataListIndex[""] = firstLevelList

	TreeTabData["首页"] = services.TreeTabInfo{Info: models.Category{Id: 0, Name: "首页"}, View: welcome.WelcomeScreen}
	for _, v := range lists {
		//二级列表
		var secondarylList []string
		for _, value := range lists {
			if v.Id == value.Pid {
				secondarylList = append(secondarylList, value.Name)
			}
		}
		if len(secondarylList) > 0 {
			dataListIndex[v.Name] = secondarylList
		}
		listData := ui.Services.GetTableData(v.Id) //获取密码数据
		v.List = listData

		// 使用函数工厂
		makeTableUiFunc := ui.createTableViewFunc(v.Name, listData)
		TreeTabData[v.Name] = services.TreeTabInfo{Info: v, View: makeTableUiFunc}
	}

	return dataListIndex
}

// 独立的视图创建函数
func (ui *MainWindow) createTableViewFunc(name string, data []models.Password) func(fyne.Window) fyne.CanvasObject {
	return func(w fyne.Window) fyne.CanvasObject {
		return ui.MakeTableUI(w, name, data)
	}
}

func (ui *MainWindow) ShowCategoryWindow() func() {
	return func() {
		categoryList, nameList := ui.Services.GetCategoryList()
		var categoryId int
		selectCategoryBox := widget.NewSelect(nameList, func(val string) {
			for _, v := range categoryList {
				if v.Name == val {
					// fmt.Println("选中的分类ID:", v.Id)
					categoryId = v.Id
				}
			}
		})
		selectCategoryBox.PlaceHolder = "请选择类型"
		nameInput := widget.NewEntry()
		descInput := widget.NewEntry()

		items := []*widget.FormItem{
			widget.NewFormItem("分类", selectCategoryBox),
			widget.NewFormItem("名称", nameInput),
			widget.NewFormItem("描述", descInput),
			widget.NewFormItem("", widget.NewLabel("")),
		}

		form := dialog.NewForm("新建分类", "保存", "取消", items, func(b bool) {
			if !b {
				return
			}
			category := new(models.Category)
			category.Pid = categoryId
			category.Name = nameInput.Text
			category.Desc = descInput.Text

			if err := ui.Services.SaveCategory(category); err != nil {
				fmt.Println("保存分类失败", err)
			}
			ui.RefreshTree()
		}, ui.Window)
		// 设置对话框大小
		form.Resize(fyne.NewSize(400, 200))
		form.Show()
	}
}

func (ui *MainWindow) LoginWindow() {
	passwordInput := widget.NewEntry()

	items := []*widget.FormItem{
		widget.NewFormItem("", widget.NewLabel("")),
		widget.NewFormItem("密码", passwordInput),
		widget.NewFormItem("", widget.NewLabel("")),
	}
	var form *dialog.FormDialog
	form = dialog.NewForm("登录", "登录", "取消", items, func(confirmed bool) {
		if !confirmed {
			// 确定按钮
			if passwordInput.Text == "" {
				dialog.ShowInformation("提示", "请输入密码", ui.Window)
				return
			}

			if passwordInput.Text == "123" {
				form.Hide()
			}
		} else {
			// 取消按钮
			// 关闭对话框
			return
		}

	}, ui.Window)
	// 设置对话框大小
	form.Resize(fyne.NewSize(200, 200))
	form.Show()
}

// 导出文件
func (ui *MainWindow) exportFile() func() {
	return func() {
		// 创建文件保存对话框
		saveDialog := dialog.NewFileSave(func(file fyne.URIWriteCloser, err error) {
			if err != nil {
				dialog.ShowError(err, ui.Window)
				return
			}
			if file == nil {
				// 用户取消了操作
				return
			}

			var content string
			for _, value := range TreeTabData {

				titleStr := "name: %s \n\n"
				content += fmt.Sprintf(titleStr, value.Info.Name)
				for _, val := range value.Info.List {
					curStr := "    name: %s \n    username: %s \n    password: %s \n    desc: %s \n"
					//字符串拼接
					content += fmt.Sprintf(curStr, val.Name, val.Username, val.Password, val.Desc)
					if val.CustomContent != nil && len(val.CustomContent) > 0 {
						for _, v := range val.CustomContent {
							curStr = "    " + v.Input_type + ": %s \n"
							//字符串拼接
							content += fmt.Sprintf(curStr, v.Content)
						}
						content += "  ---------------------\n\n"
					} else {
						content += "  ---------------------\n\n"
					}
				}
			}
			data := []byte(content)
			// 处理文件保存逻辑
			defer file.Close()
			// 示例：写入内容
			file.Write(data)
		}, ui.Window)

		// 设置标题
		// saveDialog.SetTitleText("保存配置文件")

		saveDialog.SetDismissText("取消") // 可选，默认为"取消"

		// 设置确认按钮文本
		saveDialog.SetConfirmText("导出")

		// 设置预填充的文件名
		saveDialog.SetFileName("passTree.txt")

		/* // 可选：限制文件类型
		saveDialog.SetFilter(&dialog.SaveFileFilter{
			Extensions: []string{".txt", ".md"},
			MimeType:   []string{"text/plain"},
		}) */

		saveDialog.Show()
	}
}

// 导出备份
func (ui *MainWindow) exportBackups() func() {
	return func() {
		// 创建文件保存对话框
		saveDialog := dialog.NewFileSave(func(file fyne.URIWriteCloser, err error) {
			if err != nil {
				dialog.ShowError(err, ui.Window)
				return
			}
			if file == nil {
				// 用户取消了操作
				return
			}

			var content string
			for _, value := range TreeTabData {

				titleStr := "name: %s \n\n"
				content += fmt.Sprintf(titleStr, value.Info.Name)
				for _, val := range value.Info.List {
					curStr := "    name: %s \n    username: %s \n    password: %s \n    desc: %s \n"
					//字符串拼接
					content += fmt.Sprintf(curStr, val.Name, val.Username, val.Password, val.Desc)
					if val.CustomContent != nil && len(val.CustomContent) > 0 {
						for _, v := range val.CustomContent {
							curStr = "    " + v.Input_type + ": %s \n"
							//字符串拼接
							content += fmt.Sprintf(curStr, v.Content)
						}
						content += "  ---------------------\n\n"
					} else {
						content += "  ---------------------\n\n"
					}
				}
			}
			data := []byte(content)
			// 处理文件保存逻辑
			defer file.Close()
			// 示例：写入内容
			file.Write(data)
		}, ui.Window)

		// 设置标题
		// saveDialog.SetTitleText("保存配置文件")

		saveDialog.SetDismissText("取消") // 可选，默认为"取消"

		// 设置确认按钮文本
		saveDialog.SetConfirmText("导出")

		// 设置预填充的文件名
		saveDialog.SetFileName("passTreeBackups.txt")

		saveDialog.Show()
	}
}
